package com.amarsoft.dexpre.comm.client;

import com.amarsoft.are.ARE;
import com.amarsoft.are.log.Log;
import com.amarsoft.dexpre.exception.CommException;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;

public class SocketSender
  implements Sender
{
  private String IP;
  private String Port;
  private Socket client;
  private final int TIME_OUT = 30000;
  private final int BUFF_LEN = 5000;

  public SocketSender(HashMap<String, String> dpMap) { this.IP = ((String)dpMap.get("IP"));
    this.Port = ((String)dpMap.get("Port"));
  }

  private byte[] readGzclf(Socket socket)
    throws IOException
  {
    InputStream is = socket.getInputStream();
    DataInputStream dis = new DataInputStream(is);
    int length = dis.readInt();
    length = Integer.reverseBytes(length);
    if (length > 0) {
      ARE.getLog().debug(socket + "Indicated message length(byte based): " + length);
      byte[] payload = new byte[length];
      dis.readFully(payload);
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(buffer);
      dos.writeInt(Integer.reverseBytes(length));
      dos.write(payload);
      return buffer.toByteArray();
    }
    throw new RuntimeException("error message length:" + length);
  }

  public Object execute(Object requestedData) throws Exception
  {
	  System.out.println(new String((byte[])requestedData));
    byte[] returnBytes = (byte[])null;
    try {
      this.client = new Socket(this.IP, Integer.parseInt(this.Port));
      InputStream in = this.client.getInputStream();
      OutputStream out = this.client.getOutputStream();
      this.client.setSoTimeout(30000);
      System.out.println(new String((byte[])requestedData));
      out.write((byte[])requestedData);
      out.flush();

      byte[] barray = new byte[5000];
      int readCount = in.read(barray);
      while (in.available() > 0) {
        byte[] newarray = new byte[barray.length * 2];
        System.arraycopy(barray, 0, newarray, 0, readCount);
        barray = newarray;
        readCount += in.read(barray, readCount, barray.length - readCount);
      }
      if (readCount != barray.length) {
        byte[] result = new byte[readCount];
        System.arraycopy(barray, 0, result, 0, readCount);
        barray = result;
      }
      returnBytes = barray;

      in.close();
      out.close();
      this.client.close();
    } catch (Exception e) {
      throw new CommException("Socket Send Message (IP=" + this.IP + "  Port=" + this.Port + ")", e);
    }
    return returnBytes;
  }
}